import { reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLoginOut } from "@/api"
import {setToken,getToken,removeToken} from '@/utils/token'

// 登录与注册的模块
const state = {
    code:'',
    token: getToken(),
    userInfo:''
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    // 清除本地数据
    USERLOGINOUT(state){
        // 将仓库中相关用户信息清空
        state.token = ''
        state.userInfo = {}
        //清空本地存储数据 
        removeToken()
    }
}
const actions = {
    // 获取验证码
    async getCode({commit},phone){
        let result = await reqGetCode(phone)
        if(result.code == 200){
            commit('GETCODE',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户注册
    async userRegister({commit},data){
        let result = await reqUserRegister(data)
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户登录
    async userLogin({commit},data){
        let result = await reqUserLogin(data)
        // 服务器下发token，用户唯一的标识符
        // 带着token向服务器要数据
        if(result.code==200){
            // 已经登录且获得了token
            commit('USERLOGIN',result.data.token);
            // 持久化存储token
            setToken(result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo()
        if(result.code==200){
            commit('GETUSERINFO',result.data);
            return 'ok'
        }else{
            return Promise.reject(new Error('falie'))
        }
    },
    // 退出登录
    async userLoginOut({commit}){
        let result = await reqLoginOut()
        // action中不能操作state
        if(result.code == 200){
            commit('USERLOGINOUT')
        }
    },
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}